package com.ydl.partitionscheduler.builder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.List;

@Component
public class PartitionStatementBuilderFactory {

    private final List<PartitionStatementBuilder> builders;
    private final DataSource dataSource;

    @Autowired
    public PartitionStatementBuilderFactory(List<PartitionStatementBuilder> builders, DataSource dataSource) {
        this.builders = builders;
        this.dataSource = dataSource;
    }

    public PartitionStatementBuilder getBuilder() {
        try (Connection connection = dataSource.getConnection()) {
            DatabaseMetaData metaData = connection.getMetaData();
            String databaseProductName = metaData.getDatabaseProductName();

            for (PartitionStatementBuilder builder : builders) {
                if (builder.supports(databaseProductName)) {
                    return builder;
                }
            }

            throw new UnsupportedOperationException("不支持的数据库类型: " + databaseProductName);
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库元数据失败", e);
        }
    }
}
